<?php
namespace app\wechat\controller;

use app\wechat\controller\Base;
use app\wechat\model\OauthUser;
use Overtrue\Socialite\Exceptions\AuthorizeFailedException;
use think\Log;
use think\Session;

class User extends Base
{
    public function login()
    {
        $oauth = $this->app->oauth;
        if (!Session::get('wechat_user')) {
            !Session::get('target_url') && Session::set('target_url', url('/', null, null, true));
            $redirectUrl = $oauth->redirect();
            $this->redirect($redirectUrl);
        }
        $this->redirect('/');
    }

    public function callback()
    {
        $oauth = $this->app->oauth;
        $code = $this->request->get('code');
        try {
            $data = $oauth->userFromCode($code);
            Log::info('登录用户: '.var_export($data, true));
            $openid = $data->getId();
        } catch (AuthorizeFailedException $e) {
            Log::error($e);
            return 'ERROR';
        }
        $oauth_user = OauthUser::where('openid', $openid)->find();
        if ($oauth_user){
            foreach ($data->getRaw() as $key => $value) {
                if (isset($oauth_user->$key)) {
                    $oauth_user->$key = $value;
                }
            }
        } else {
            $oauth_user = new OauthUser($data->getRaw());
            $oauth_user->allowField(true);
        }
        $oauth_user->save();
        Session::set('wechat_user', $oauth_user->toArray());
        $targetUrl = Session::get('target_url') ?:'/';
        $this->redirect($targetUrl);
    }
}